layui.use(['form', 'layer', 'table', 'tree'], function () {

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        tree = layui.tree,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var handle_url = $('.handle_url').val();
    var getMenus_url = $('.getMenus_url').val();


    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url: datalist_url,
        page: true,
        cellMinWidth: 95,
        //height : "full-100",
        limit: 10,
        limits: [10, 20, 50, 100],
        id: "tableList",
        cols: [[
            /*{type: "checkbox", fixed:"left", width:50},*/
            {field: 'id', title: '序号', width:80, align: "center"},
            {field: 'name', title: '角色名称', align: "center"},
            {
                field: 'status', title: '禁用与启用', align: "center", templet: function (data) {
                    var html = '';
                    if (data.status == 1) {
                        html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="' + data.id + '" checked>';
                    } else {
                        html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="' + data.id + '">';
                    }

                    return html;
                }
            },
            {
                title: '操作', fixed: "right", align: "center", minWidth: 140, templet: function (data) {
                    var html = '';
                    html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';

                    return html;
                }
            }
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function () {
        var name = $('.searchBox').find('input[name=name]').val();

        if (name != '') {
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: name,
                }
            });
        } else {
            layer.msg("请选择筛选条件");
        }
    });

    // 清空搜索
    $(".reset_btn").on("click", function () {
        table.reload("tableList", {
            where: {
                name: '',
            }
        });
    });

    $('.add_btn').on('click', function () {
        formHtml();
    });

    // 列表操作
    table.on('tool(dataTable)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;
        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if (layEvent === 'edit') {
            formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data) {
        var content = add_url;

        if (data) {
            content = edit_url + '?id=' + data.id;
        }

        var index = layer.open({
            title: "角色管理",
            type: 2,
            area: ["600px", "500px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    }

    form.on('switch(status)', function (data) {
        var index = layer.msg('修改中，请稍候', {icon: 16, time: false, shade: 0.8});

        var status = 2;
        if (data.elem.checked) {
            status = 1;
        }
        $.ajax({
            url: handle_url,
            data: {'id': data.elem.value, 'status': status},
            type: "post",
            dataType: "json",
            success: function (res) {
                top.layer.close(index);
                top.layer.msg(res.msg);
                if (res.code == 1) {
                    parent.layui.table.reload('tableList', {});
                } else {
                    data.elem.checked = !data.elem.checked;
                    form.render();
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    });

    if ($('#role_tree').length > 0) {
        var id = $('input[name=id]').val();
        if (id) {
            getMenus_url += '?id=' + id;
        }

        var role_tree = new layuiXtree({
            elem: 'role_tree'                  //必填
            , form: form                    //必填
            , data: getMenus_url //必填
            , isopen: false  //加载完毕后的展开状态，默认值：true
            , ckall: true    //启用全选功能，默认值：false
            , ckallback: function () {

            } //全选框状态改变后执行的回调函数
            , icon: {        //三种图标样式，更改几个都可以，用的是layui的图标
                open: "&#xe625"       //节点打开的图标
                , close: "&#xe623"    //节点关闭的图标
                //, end: "&#xe621"      //末尾节点的图标
                , end: ""      //末尾节点的图标
            }
            , color: {       //三种图标颜色，独立配色，更改几个都可以
                open: "#017dda"        //节点图标打开的颜色
                , close: "#1e9fff"     //节点图标关闭的颜色
                , end: "#828282"       //末级节点图标的颜色
            }
            , click: function (data) {  //节点选中状态改变事件监听，全选框有自己的监听事件
                // console.log(data.elem); //得到checkbox原始DOM对象
                // console.log(data.elem.checked); //开关是否开启，true或者false
                // console.log(data.value); //开关value值，也可以通过data.elem.value得到
                // console.log(data.othis); //得到美化后的DOM对象
            }
        });
    }

    // 表单提交
    form.on("submit(laySave)", function (data) {
        // 获得选中的节点
        var checkData = role_tree.GetChecked();
        console.log(checkData);
        if (checkData.length <= 0) {
            layer.msg("至少选择一项权限");
            return false;
        }

        var role_list = [];
        for (let i = 0; i < checkData.length; i++) {
            role_list.push(checkData[i].value);
            // 父节点
            var parent_role = role_tree.GetParent(checkData[i].value);
            if (parent_role) {
                if ($.inArray(parent_role.value, role_list) < 0) {
                    role_list.push(parent_role.value);
                }
            }
        }
        //console.log(role_list);
        data.field.access = role_list;

        if (data.field.status == 'on') {
            data.field.status = 1;
        } else {
            data.field.status = 2;
        }

        submitForm(data);
    });

    // 表单提交
    function submitForm(data) {
        // 弹出loading
        var index = layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function (res) {
                layer.msg(res.msg);
                if (res.code == 1) {
                    layer.closeAll("iframe");
                    //parent.window.tableIns.reload();
                    parent.layui.table.reload('tableList', {});
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    }
});